<?php

class Upload{
	
	private $max_size = 1000000;//文件上传的大小  1M
	private $ext_arr = array('jpg','gif','png');//上传文件类型
	
	public function __construct( $max_size = 0, $ext_arr = array() ){
		if( $max_size != 0 ) $this->max_size = $max_size;
		if( !empty( $ext_arr ) ) $this->ext_arr = $ext_arr;
	}
	
	//note 判断是否是支持上传文件类型
	private function judgeType( $filetype ){
		return in_array( $filetype, $this->ext_arr );
	}

	//note 取得文件扩展名
	private function getExt( $pic ){
		return strtolower( end( explode( '.', $pic ) ) );
	}
   
   
   // upfile  文件路径   
   private function getName($upfile, $pic, &$newname){
	   
	   $upfile = trim( str_replace('\\','/',$upfile) );	// 转义路径
	   
		if( substr($upfile,-1,1) != '/'){
			 $upfile	=  $upfile.'/';	
		}
		
		$dir	= $upfile;
	   if(!is_dir($dir)){
		  @mkdir($dir,0777);
	   }
	   
	   $exname		= $this->getExt($pic);	
		$i			= 1;
		$filename	= time().rand(1000,9999);
	   	while(true){
			$name = $filename.$i.".".$exname;
		   if(!@is_file($dir.$name)){
			   break;
			}
	  		$i++;
		}
		$newname = $name;
		return ($dir.$name);
   }

    /**
     * @param string $upfile 上传路径
     * @param string $pic 上传文件域名
     * @param integer $type 上传错误类型
     * @return false或上传后文件名称
     * */
	public function doUpload( $upfile, $pic, &$type=0 ){
		
		if(empty($_FILES[$pic]) || empty($_FILES[$pic]['name'])){	// 空
			$type	= 10;	// 空格式
			return false;
		}
		$exname	= $this->getExt( $_FILES[$pic]['name'] );
		if(!$this->judgeType($exname)){	// 非法格式
			$type	= 11;  //非法格式
			return false;
		}
		
		
		if($_FILES[$pic]['size'] >= $this->max_size ){	// 超过大小
			$type	= 12;	// 超过大小
			return false;
		}
		
		$newname = '';
		$uploadfile = $this->getName($upfile, $_FILES[$pic]['name'],$newname);
		
		if(move_uploaded_file($_FILES[$pic]['tmp_name'], $uploadfile)){
			$ret = $newname;
		}else{
			$type 	= 13;	// 无法写入到服务器
			return false;
		}
		
		return $ret;
	}
	
	
	public function getErr( $type ){
		$err = array(	'10' => '上传文件为空！',
						'11' => '不支持此格式文件上传',
						'12' => '上传文件过大',
						'13' => '无法写入到服务器'
				);
		return $err[$type];
	}

	
}

?>